package net.entelijan.cobean.examples.showcase.config.table;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JOptionPane;

import net.entelijan.cobean.core.ColumnDesc;
import net.entelijan.cobean.data.literature.ILitService;
import net.entelijan.cobean.data.literature.LitBook;
import net.entelijan.cobean.examples.util.ExamplesUtil;
import net.entelijan.config.CobeanConfigFactory;
import net.entelijan.config.ICobeanConfig;
import net.entelijan.scf.IShowcase;

public class ConfigTableShowcase implements IShowcase<ConfigTablePanel> {

	private ILitService service = null;

	private SingleSelectionModel model = new SingleSelectionModel();

	public ConfigTableShowcase() {
		super();
	}

	@Override
	public void init(final ConfigTablePanel view) {

		// Binds the table contents and selections to the model appropriate
		// properties.
		ICobeanConfig cfg = CobeanConfigFactory.createConfig();
		model = cfg.bind(model, view, ColumnDesc
				.createFilterableSortableColumnDescs("title,Title",
						"year,Year", "author.name,Author"));

		// Set some books to the model. As they are bound to the JTable they
		// appear (automatically) on the GUI.
		model.setBooks(service.loadAllBooks());

		view.getShowAllBooks().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(view, ExamplesUtil.listToString(
						model.getBooks(), 100));
			}

		});

		view.getShowSelecedBook().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(view, model
						.getBooksSelectedValue());
			}

		});

		view.getSelectFirstBookButton().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				model.setBooksSelectedValue(model.getBooks().get(0));
			}

		});

		view.getSelectThirdBookButton().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				model.setBooksSelectedValue(model.getBooks().get(2));
			}

		});

		view.getDeleteBookButton().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				LitBook selBook = model.getBooksSelectedValue();
				if (selBook == null) {
					JOptionPane.showMessageDialog(view, "No book is selected!");
				} else {
					List<LitBook> books = model.getBooks();
					books.remove(selBook);
				}
			}

		});

	}

	public SingleSelectionModel getModel() {
		return model;
	}

	public void setModel(SingleSelectionModel model) {
		this.model = model;
	}

	public ILitService getService() {
		return service;
	}

	public void setService(ILitService service) {
		this.service = service;
	}

}
